package com.hedl.classroom.service.impl;

import com.hedl.classroom.service.SendCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Big Watermelon
 * @description
 * @date 2023/12/13/16:08
 */
@Service
@Slf4j
public class SendCodeServiceImpl implements SendCodeService {

    @Autowired
    private JavaMailSender javaMailSender;
    public final Long CODE_TTL = 120L;

    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void sendEMail(String email, String code) {
        // 1. 向用户发送验证码
        sendTestMail(email, code);
        // 2. 将验证码缓存到redis，TTL设置为2分钟
        redisTemplate.opsForValue().set(email, code, CODE_TTL, TimeUnit.SECONDS);
    }

    /**
     * 发送邮件
     * @param email 收件邮箱号
     * @param code 验证码
     */
    @Override
    public void sendTestMail(String email,String code) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from);
        mailMessage.setTo(email);
        mailMessage.setSubject("学成在线登陆邮箱验证码：");
        mailMessage.setText("尊敬的用户:你好!你的验证码为: "+code+" (有效期为一分钟,请勿告知他人)");
        javaMailSender.send(mailMessage);
    }

    /**
     * 生成验证码
     * @return
     */
    @Override
    public String achieveCode() {
        //由于数字 1 、 0 和字母 O 、l 有时分不清楚，所以，没有数字 1 、 0
        String[] beforeShuffle = new String[]{"2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
                "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a",
                "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
                "w", "x", "y", "z"};
        //将数组转换为集合
        List<String> list = Arrays.asList(beforeShuffle);
        //打乱集合顺序
        Collections.shuffle(list);
        StringBuffer sb = new StringBuffer();
        for (String s : list) {
            //将集合转化为字符串
            sb.append(s);
        }
        return sb.substring(3,8);
    }

}
